package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-ease/cache"
	"recruit-ease/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var count int64
	models.DB.Model(&models.HotWork{}).Count(&count)
	var work []models.HotWork

	redis_key := "work_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Order("id desc").Offset(offset).
			Limit(size).Find(&work)
		jsonData, _ := json.Marshal(work)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &work)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表展示成功",
		"data":  work,
		"count": count,
	})

}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var work models.HotWork

	redis_key := "work_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&work)
		jsonData, _ := json.Marshal(work)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &work)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情展示成功",
		"data": work,
	})
}
func Coll(c *gin.Context) {

}
